# -*- coding:utf-8 -*-
'''视频画面旋转'''
from tkinter import *
from tkinter import ttk
from tkinter.ttk import *
import tkinter.messagebox
import tkinter as tk
from tkinter import filedialog
from media import basic
import os
import subprocess
import re
from media import mediaUtil
import threading
from components.DictComboBox import DictComboBox

class vtFrame(object):
    def __init__(self,parent):
        self.root = tkinter.Toplevel(parent)
        self.root.title('视频画面旋转')
         #子窗口随着主窗口关闭或最小化
        self.root.transient(parent)
        self.root.resizable(False, False)
        self.root.minsize(480, 135)
        self.centerWin(self.root,480, 135)
        
        #用于保存视频帧率（单位:kb/s）
        self.bitrate=None
        
        tspFrame = ttk.Frame(self.root)
        bm = PhotoImage(file = mediaUtil.SOURCE_PATH+'transpose.png')
        tipLabel = Label(tspFrame,image=bm)
        tipLabel.bm = bm
        tipLabel.grid(row=0,column=0,rowspan=6,padx=5,pady=5,sticky=(N, W, E, S))
        
        videoLabel = Label(tspFrame,text='视频文件：')
        videoLabel.grid(column=1, row=2,padx=3,sticky=(N, W, E, S))
        self.videoString = StringVar()
        self.videoPath = Entry(tspFrame,textvariable = self.videoString,width=30,state=DISABLED)
        self.videoPath.grid(column=2, row=2,padx=3,sticky=(W, E))
        videoPathBtn = ttk.Button(tspFrame,text="选择文件",width=10,command=self.getVideoPath).grid(row=2,column=3,sticky=W+E,padx=10)

        outLabel = Label(tspFrame,text='存放文件夹：')
        outLabel.grid(column=1, row=3,padx=3,sticky=(N, W, E, S))
        self.video2String = StringVar()
        self.video2Path = Entry(tspFrame,textvariable = self.video2String,width=30,state=DISABLED)
        self.video2Path.grid(column=2, row=3,padx=3,sticky=(W, E))
        audioPathBtn = ttk.Button(tspFrame,text="选择文件夹",width=10,command=self.getVideo2Path).grid(row=3,column=3,sticky=W+E,padx=10)

        rotateLabel = Label(tspFrame,text='旋转角度：')
        rotateLabel.grid(column=1, row=7,padx=3,sticky=(N, W, E, S))
        data = {"顺时针旋转180度":180}
        self.rotate = DictComboBox(tspFrame,data)
        self.rotate.current(0)
        self.rotate.grid(row=7,column=2,padx=5,sticky=(W,S))
        self.execBtn = ttk.Button(tspFrame,text="旋转",width=10,command=self.videoTSP)
        self.execBtn.grid(row=7,column=3,sticky=W+E,padx=10)
        
        self.statusLabel = Label(tspFrame,text='已就绪',relief=GROOVE,anchor=W)
        self.statusLabel.grid(row=8,column=0,columnspan=4,pady=6,sticky=(N, W, E, S))

        tspFrame.grid(row=0,column=0,pady=5,sticky=(N, W, E, S))
        
        
    '''窗口居中'''
    def centerWin(self,root,width,height):
        screenwidth = root.winfo_screenwidth()
        screenheight = root.winfo_screenheight()
        size = '%dx%d+%d+%d' % (width, height, (screenwidth - width)/2, (screenheight - height)/2)  
        root.geometry(size)
        
        '''获取视频文件地址'''
    def getVideoPath(self):
        self.videoString.set('')
        path = filedialog.askopenfilename()
        if path !="":
            ext = os.path.splitext(path)[1][1:]
            isVideo = 0
            for et in basic.VIDEOS:
                if et == ext:
                    isVideo = 1
            if isVideo == 1:
                self.videoString.set(path)
            else:
                tkinter.messagebox.showerror("提示","请选择视频文件")
        cmd = mediaUtil.cmd_mediaInfo(path)
        if cmd == None:
            tkinter.messagebox.showerror("提示","无法获取视频信息命令")
            return Flase
        subprocess.call(cmd)
        result = subprocess.getoutput(cmd)
        #获取视频帧率
        b = re.search(r'bitrate: (\d+) kb', result)
        #获取原视频的比特率
        self.bitrate = b.group(1)
        
    '''获取视频提取的存放路径'''
    def getVideo2Path(self):
        path = filedialog.askdirectory()
        if path !="":
            self.video2String.set(path)
    
    '''视频画面旋转函数'''
    def videoTSP(self):
        videoPath = self.videoString.get()
        if videoPath == "":
            tkinter.messagebox.showerror("提示","请选择视频文件")
            return False
        video2Path = self.video2String.get()
        if video2Path =="":
            tkinter.messagebox.showerror("提示","请选择存放文件夹")
            return False
        videoName = os.path.basename(videoPath)
        ret = list(re.finditer('\.', videoName))
        videoName = videoName[0:ret[-1].span()[0]]
        ext = os.path.splitext(videoPath)[1][1:]
        outputFile = video2Path+'/{0}.{1}'.format(videoName,ext)
        cmd = mediaUtil.cmd_getVideoTSP(videoPath, outputFile, self.rotate.getValue(), self.bitrate)
        if cmd is None:
            tkinter.messagebox.showerror("提示","无法获取视频旋转命令")
        self.statusLabel['text']='旋转中'
        subprocess.Popen(cmd)
        #禁用旋转按钮
        self.execBtn.config(state=DISABLED)
        tps_thread = threading.Thread(target=self.getTSPProgress,args=(None,cmd))
        tps_thread.start()
        
    
    def getTSPProgress(self,x,cmd):
        try:
            iscomplete = 0
            while iscomplete ==0:
                info = mediaUtil.getCmdExecInfo(cmd)
                if info !="":
                    iscomplete=1
            if iscomplete ==1:
                self.statusLabel['text']='旋转成功'
            #启用旋转按钮
            self.execBtn.config(state=NORMAL)
        except:
            self.statusLabel['text']='旋转失败'
        
        
        